<?php

namespace app\admin\controller\bot;

use app\common\controller\AdminController;
use app\common\services\annotation\ControllerAnnotation;
use app\common\services\annotation\NodeAnnotation;

use support\Request; //请求类
use support\Response; //请求类
use think\facade\Db; //数据库类
use think\App; //初始化
use think\Exception; //异常
/**
 * @ControllerAnnotation(title="bot_text")
 */
class TextController extends AdminController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\BotText();
    }

    public function index(Request $request): Response{
        $gfid = $request->get('id');
        if(!$gfid){
           $gfid = "-1" ;
        }
        if (!$request->isAjax()) return view('admin/bot/text/index',['gfid'=>$gfid]);
        if ($request->input('selectFields')) {
            return $this->selectList();
        }
        list($page, $limit, $where) = $this->buildTableParams();
        $count = $this->model->where($where)->count();
        $list  = $this->model->where($where)->order($this->order)->page($page, $limit)->select()->toArray();
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }
    
    public function add(Request $request): Response
    {
        $gfid = $request->get('id');
        if(!$gfid){
           $gfid = "-1" ;
        }
        $info = DB::name('bot_list')->where('id',$gfid)->find();
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch('admin/bot/text/add',['info'=>$info]);
    }
    public function edit(Request $request)
    {
        $id  = (int)$request->input('id');
        $row = $this->model->find($id);
        if (empty($row)) return $this->error('数据不存在');
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                $save = $row->save($post);
            } catch (\PDOException|\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign(compact('row'));
        return $this->fetch('admin/bot/text/edit');
    }
}
